Macromedia Flex Article

Learning Flex Basics (Part 2): Creating a Simple Calculator with Macromedia Flex


Table of Contents

  1. Introduction
  2. Building the Calculator
  3. Create the Application Object
  4. Add a Panel for the Calculator
  5. Add the Calculator Display
  6. Add a Grid to Lay Out the Buttons
  7. Add the Calculator Buttons
  8. Create the CalculatorController Class
  9. Add Properties to the Controller Class
  10. Add Controller Methods
  11. Instantiate the CalculatorController Class
  12. Complete Code Listing for calculator.mxml
  13. Complete Code Listing for CalculatorController.as
  14. Where to Go From Here

Add the Calculator Buttons

The Flex Button control is similar to buttons in HTML and other languages. You will use three properties for the buttons:

  • label: the text displayed on the button
  • width
  • click: the name of the handler executed when the user clicks on the button

Each button in your calculator will have the same general syntax:

<mx:Button label="[something]" width="[number]" click="[some handler method]"/>

Note: The following steps contain the names of event handlers that don't exist yet; you will create the handlers later as part of the CalculatorController class.

  1. Add a Button element inside each of the 18 GridItem containers; in the order of the GridItem containers, the Buttons will have the following properties:

    Row 1

    	width="70" 
    	label="Clear" 
    	click="calcController.clearAll()"
     
    	width="30"
    	label="C/E" 
    	click="calcController.clearEntry()"
    
    	width="30"
    	label="+" 
    	click="calcController.setOperation('add')"
    

    Row 2

    	width="30" 
    	label="1" 
    	click="calcController.addNumber('1')"
    	
    	width="30" 
    	label="2"
    	click="calcController.addNumber('2')"
    	
    	width="30" 
    	label="3" 
    	click="calcController.addNumber('3')"
    	
    	width="30" 
    	label="-" 
    	click="calcController.setOperation('subtract')"
    

    Row 3

    	width="30" 
    	label="4" 
    	click="calcController.addNumber('4')"
    	
    	width="30" 
    	label="5" 
    	click="calcController.addNumber('5')"
    	
    	width="30" 
    	label="6" 
    	click="calcController.addNumber('6')"
    	
    	width="30" 
    	label="*" 
    	click="calcController.setOperation('multiply')"
    

    Row 4

    	width="30" 
    	label="7" 
    	click="calcController.addNumber('7')"
    	
    	width="30" 
    	label="8" 
    	click="calcController.addNumber('8')"
    	
    	width="30" 
    	label="9" 
    	click="calcController.addNumber('9')"
    	
    	width="30" 
    	label="/" 
    	click="calcController.setOperation('divide')"
    

    Row 5

    	width="30" 
    	label="0" 
    	click="calcController.addNumber('0')"
    	
    	width="30" 
    	label="." 
    	click="calcController.addNumber('.')"
    	
    	width="70" 
    	label="=" 
    	click="calcController.doOperation()"
    
  2. Save the file.